package com.demo.zookeeper.controller;

import com.demo.zookeeper.zkmanager.ZkClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class ZkTest {

  @Autowired
  private ZkClient zkClient;

  @GetMapping("/ZkNodeTest")
  public String zkNodeTest(){
    log.info("接收到 zkNodeTest 请求");
    try {
      zkClient.connectZk();
      String node = "/Node1";
      Stat stat = new Stat();
      zkClient.addNode(node, "123");
      zkClient.modifyNodeData(node, "567".getBytes());
      zkClient.getNodeData(node, stat);
      log.info("{}", stat);
      zkClient.deleteNote(node);
    } catch (Exception e) {
      log.info("{}", e);
    } finally {
      zkClient.closeZk();
    }
    return "Okay";
  }

  @GetMapping("/zkTransactionRB")
  public String zkTransactionRB(){
    log.info("接收到 zkTransaction 请求");
    try {
      zkClient.connectZk();
      zkClient.zkTransactionRollback();
    } catch (Exception e) {
      log.info("{}", e);
    } finally {
      zkClient.closeZk();
    }
    return "Okay";
  }

  @GetMapping("/zkTransactionCommit")
  public String zkTransactionCommit(){
    log.info("接收到 zkTransactionCommit 请求");
    try {
      zkClient.connectZk();
      zkClient.zkTransactionCommit();
    } catch (Exception e) {
      log.info("{}", e);
    } finally {
      zkClient.closeZk();
    }
    return "Okay";
  }

  @GetMapping("/zkListen")
  public String zkListen(){
    log.info("接收到 zkListen 请求");
    try {
      zkClient.connectZk();
      zkClient.zkListen();
    } catch (Exception e) {
      log.info("{}", e);
    } finally {
      zkClient.closeZk();
    }
    return "Okay";
  }

}


